package hu.tortavar.server;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;

import hu.tortavar.client.Termek;
import hu.tortavar.client.TermekService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;


public class TermekServiceImpl extends RemoteServiceServlet implements
		TermekService {

	private static final Logger LOG = Logger.getLogger(TermekServiceImpl.class.getName());	
	private static final PersistenceManagerFactory PMF =
			JDOHelper.getPersistenceManagerFactory("transactions-optional");

	@SuppressWarnings("unchecked")
	@Override
	public List<Termek> getTermekek(int csoport) {
		PersistenceManager pm = getPersistenceManager();
		
		Query q = pm.newQuery(Termek.class);
		q.setFilter("csoport == csoportP");
		q.setOrdering("csoport ascending, cim ascending");
		q.declareParameters("int csoportP");
		
		try {
			List<Termek> termekek = (List<Termek>) q.execute(csoport);
			return (List<Termek>) pm.detachCopyAll(termekek);
		} finally {
			pm.close();
		}
	}

	@Override
	public void addTermek(String megnevezes, String leiras, String imageURL, int csoport,
			boolean hire, String ar) {
		// TODO Auto-generated method stub
		PersistenceManager pm = getPersistenceManager();
		try {
			pm.makePersistent(new Termek(megnevezes, leiras, imageURL, csoport, hire, ar));
		} finally {
			pm.close();
		}
	}
	
	private PersistenceManager getPersistenceManager() {
		return PMF.getPersistenceManager();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Termek> getNews() {
		PersistenceManager pm = getPersistenceManager();
		
		Query q = pm.newQuery(Termek.class);
		q.setFilter("csoport == csoportP");
		q.setOrdering("createDate");
		q.declareParameters("int csoportP");
		q.setRange(0,1);
		
		try {
			List<Termek> hirek = (List<Termek>) q.execute(0);
			if (!hirek.isEmpty()) {
				return (List<Termek>) pm.detachCopyAll(hirek);
			} else {
				hirek.add(new Termek("Ez biza", "Teljesen üres", "/images/ures.png", 0, true, ""));
				return (List<Termek>) pm.detachCopyAll(hirek);
			}
		} finally {
			pm.close();
		}
	}
}
